<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="82px" l>

      <el-form-item label="子系统名称">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入子系统名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable>
          <el-option
              v-for="dict in subsys_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:subSystem:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:subSystem:edit']"
        >修改</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="danger"-->
<!--            plain-->
<!--            icon="Delete"-->
<!--            :disabled="multiple"-->
<!--            @click="handleDelete"-->
<!--            v-hasPermi="['system:subSystem:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="子系统标识" align="center" prop="subsysId" />
      <el-table-column label="子系统名称" align="center" prop="name" />
      <el-table-column label="子系统路径" align="center" prop="uri" />
      <el-table-column label="显示排序" align="center" prop="order" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="subsys_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:subSystem:edit']"
          >修改</el-button>
          <el-button
              link
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:subSystem:remove']"
          >删除</el-button>
          <el-button
              type="primary"
              link
              @click="handleManage(scope.row)"
          >菜单管理</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body v-if="open">
      <el-form ref="postRef" :model="form" :rules="rules" label-width="100px" >
        <el-form-item label="子系统标识" prop="subsysId">
          <el-input v-model="form.subsysId" placeholder="请输入子系统标识" />
        </el-form-item>
        <el-form-item label="子系统名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入子系统名称" />
        </el-form-item>
        <el-form-item label="显示顺序">
          <el-input-number v-model="form.order" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in subsys_status"
                :key="dict.value"
                :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <div>
          <el-form-item label="子系统路径" prop="uri">
            <el-input v-model="form.uri"  placeholder="请输入子系统路径" />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="子系统描述" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </div>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormDebounceHandler">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="选择菜单" v-model="open1" width="700px" append-to-body v-if="open1">
      <div>子系统名称：<span style="font-weight: bold">{{sysName}}</span></div>
      <div style="margin-top: 20px">
        <el-tree
            class="tree-border"
            :data="deptOptions"
            show-checkbox
            default-expand-all
            ref="deptRef"
            node-key="id"
            :default-checked-keys="checkedKeys"
            empty-text="加载中，请稍候"
            :props="{ label: 'label', children: 'children' }"
        ></el-tree>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSaveMenuDebounceHandler">确 定</el-button>
          <el-button @click="open1=false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="subSystem">
import { listPost, addPost, delPost, getPost, updatePost } from "@/api/system/post";
import  {listsubsystem,addsubsystem,deletesubsystem,updatesubsystem,getMenuTree,PostgetMenuTree,selectBindMenuList} from '@/api/system/subsystem.js'
const { proxy } = getCurrentInstance();
const { sys_normal_disable,subsys_status } = proxy.useDict("sys_normal_disable","subsys_status");
import { debounce } from "@/utils/debounce.js";

const postList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const sysName=ref("")
const open1=ref(false);
const deptOptions=ref([])
const deptRef = ref(null);
const subsysId=ref('');
const checkedKeys = ref();


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name:undefined,
    status: undefined
  },
  rules: {
    subsysId: [{ required: true, message: "请输入子系统标识", trigger: "blur" }],
    name: [{ required: true, message: "请输入子系统名称", trigger: "blur" }],
    postSort: [{ required: true, message: "岗位顺序不能为空", trigger: "blur" }],
    uri: [{ required: true, message: "子系统路径不能为空", trigger: "blur" }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询岗位列表 */
function getList() {
  loading.value = true;
  listsubsystem(queryParams.value).then(response => {
    console.log('222222222',response)
    postList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    subsysId: undefined,
    uri: undefined,
    name: undefined,
    order: 0,
    status: "0",
    remark: undefined
  };
  proxy.resetForm("postRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

 function handleManage(data){
    sysName.value=data.name
    subsysId.value=data.id
   selectBindMenuList(subsysId.value).then(res=>{
     console.log(res.data.checkedMenuList)
     open1.value=true
     checkedKeys.value = res.data.checkedMenuList;

     nextTick(() => {
        deptRef.value.setCheckedKeys(res.data.checkedMenuList);
       // checkedKeys.value=res.data.checkedMenuList

     });

   })
 }
 function getMenu(){
   getMenuTree().then(res=>{
      console.log(res)
     deptOptions.value=res.data
   })
 }
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.name=''
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
const submitSaveMenuDebounceHandler = debounce(submitSaveMenu, 500);
function submitSaveMenu() {
  let arr=[]
  arr=[...deptRef.value.getCheckedKeys(),...deptRef.value.getHalfCheckedKeys()]
   console.log(arr)
  let obj={
    subsysId:subsysId.value,
    menuIdList:arr
  }
  PostgetMenuTree(obj).then(res=>{
    console.log('res',res)
    proxy.$modal.msgSuccess("设置成功");
    open1.value = false;
    getList();
  })
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增子系统";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  form.value = row;
  open.value = true;
  title.value = "修改子系统";
  // const postId = row.postId || ids.value;
  // getPost(postId).then(response => {
  //   form.value = response.data;
  //   open.value = true;
  //   title.value = "修改岗位";
  // });
}

/** 提交按钮 */
const submitFormDebounceHandler = debounce(submitForm, 500);
function submitForm() {
  proxy.$refs["postRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        updatesubsystem(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addsubsystem(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const postIds = row.id? [row.id]: ids.value;
  proxy.$modal.confirm('是否确认删除该子系统数据项？').then(function() {
    return deletesubsystem(postIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
getMenu()
getList();
</script>
